package pub.sun.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pub.sun.action.BaseAction;
import pub.sun.util.Utils;

public class DispatcherServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public DispatcherServlet() {
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String servletPath = req.getServletPath();
		String actionPath = servletPath.substring(1, servletPath.length() - 3);
		Utils utils = new Utils();
		BaseAction action = utils.getAciton(actionPath);
		String view = action.execute(req, resp);
		resp.sendRedirect(view);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String servletPath = req.getServletPath();
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		String url = "";
		String path = req.getServletPath();
		ActionBean actionbean = ActionContainer.getActionBean(path);
		BaseAction action = actionbean.getAction();
		String resultType = action.execute(req, resp);
		url = actionbean.getPath(resultType);
		RequestDispatcher dispatcher = req.getRequestDispatcher(url);
		dispatcher.forward(req, resp);
		resp.getWriter().append("Served at: ").append(req.getContextPath());
	}

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(arg0, arg1);
	}

}
